package com.ll.blog.Handler;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.SocketAddress;
import java.util.Collection;
import java.util.UUID;

@Component
@Slf4j
public class NettySocketHandler implements CommandLineRunner {
    @Autowired
    SocketIOServer socketIOServer;
    private final static String QUERY_CLIENT_ID = "clientId";


    @OnConnect
    public void onConnect(SocketIOClient client) {
        UUID address = client.getSessionId();
        System.out.println(String.format("%s连接成功", address));
    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String clientId = client.getHandshakeData().getSingleUrlParam(QUERY_CLIENT_ID);
        log.debug(String.format("%s断开连接", clientId));
    }
    @OnEvent("CommentChange")
    public void onCommentChange(SocketIOClient client, AckRequest request, Object data) {
        Collection<SocketIOClient> allClients = socketIOServer.getAllClients();
        sendAll(allClients,client,"RefreshComment");
        log.debug("评论发生变化");
    }

    public void sendAll(Collection<SocketIOClient> clients,SocketIOClient client,String eventName){
        for (SocketIOClient allClient : clients) {
            if (client.getSessionId()!=allClient.getSessionId()){
                allClient.sendEvent(eventName);
            }
        }
    }


    @Override
    public void run(String... args) throws Exception {
        socketIOServer.start();
        System.out.println("socketio 启动");
        log.info("启动");
    }
}
